<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\Cache;

class Like extends BaseController
{
    // 点赞或取消点赞
    public function like()
    {
        $param = $this->request->POST();
        $contentId = $param['contentId'];
        $userId = $param['userId'];
        $redis = Cache::store('redis')->handler();
        $likeKey = "like:{$contentId}";
        $userLikeKey = "user:{$userId}:likes";

        // 检查用户是否已经点赞
        if ($redis->hget($likeKey, $userId)) {
            // 取消点赞
            $redis->hset($likeKey, $userId, 0);
            $redis->srem($userLikeKey, $contentId);
            $redis->hincrby($likeKey, 'count', -1);
        } else {
            // 点赞
            $redis->hset($likeKey, $userId, 1);
            $redis->sadd($userLikeKey, $contentId);
            $redis->hincrby($likeKey, 'count', 1);
        }

        return json(['code' => 200, 'msg' => '操作成功']);
    }

    // 获取内容的点赞数
    public function getLikeCount()
    {
        $param = $this->request->get();
        $contentId = $param['contentId'];
        $redis = Cache::store('redis')->handler();
        $likeKey = "like:{$contentId}";
        $count = $redis->hget($likeKey, 'count');

        return json(['code' => 200, 'data' => ['count' => !$count ? 0:$count]]);
    }

    // 获取用户的点赞记录
    public function getUserLikes($userId)
    {
        $redis = Cache::store('redis')->handler();
        $userLikeKey = "user:{$userId}:likes";
        $likes = $redis->smembers($userLikeKey);

        return json(['code' => 200, 'data' => ['likes' => $likes]]);
    }
}